<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="题目类别" prop="subClass">
        <el-select v-model="queryParams.subClass" placeholder="请选择题目类别" clearable size="small">
          <el-option v-for="dict in classOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="题库类型" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择题库类型" clearable size="small">
          <el-option v-for="dict in categoryOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="题型" prop="queType">
        <el-select v-model="queryParams.queType" placeholder="请选择题型" clearable size="small">
          <el-option v-for="dict in txList" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="分数" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入分数" clearable size="small"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否必练题" prop="must" label-width="90px">
        <el-select v-model="queryParams.must" placeholder="请选择是否必练题" clearable size="small">
          <el-option v-for="dict in mustOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="题干" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入关键字" clearable size="small"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['qb:subject:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                   @click="handleUpdate" v-hasPermi="['qb:subject:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-refresh" size="mini" @click="handleCsh"
                   v-hasPermi="['qb:subject:InitSubject']">初始化题库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete" v-hasPermi="['qb:subject:remove']">删除</el-button>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['qb:subject:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目类别" align="center" prop="subClass" :formatter="subClassFormat" />
      <el-table-column label="题库类型" align="center" prop="category" :formatter="categoryFormat" />
      <el-table-column label="题型" align="center" prop="queType" :formatter="queTypeFormat" />
      <el-table-column label="题干" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="答案" align="center" prop="answer" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="是否必练题" align="center" prop="must" :formatter="mustFormat" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-coin" @click="seeTx(scope.row)">题项
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['qb:subject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['qb:subject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body
               :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="题目类别" prop="subClass">
          <el-select v-model="form.subClass" placeholder="请选择题目类别" style="width:100%">
            <el-option v-for="dict in classOptions" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="题库类型" prop="category">
          <el-select v-model="form.category" placeholder="请选择题库类型" style="width:100%">
            <el-option v-for="dict in categoryOptions" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="queType">
          <el-select v-model="form.queType" placeholder="请选择题型" style="width:100%">
            <el-option v-for="dict in txList" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="题干" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入内容" maxlength="100"
                    show-word-limit style="width:100%" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="form.answer" type="textarea" placeholder="请输入内容" maxlength="100"
                    show-word-limit style="width:100%" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input-number v-model="form.score" controls-position="right" :precision="1" :step="0.1"
                           style="width:100%" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item label="是否必练题" prop="must">
          <el-select v-model="form.must" placeholder="请选择是否必练题" style="width:100%">
            <el-option v-for="dict in mustOptions" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">
              {{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="200"
                    show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="submitForm" :loadding='saveLoading'>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="题项" :visible.sync="openTx" width="80vw" append-to-body
               :close-on-click-modal='false'>
      <el-button type="warning" plain icon="el-icon-plus" size="mini" @click="handleAddTx"
                 :disabled='allSubItemList.length===5' v-hasPermi="['qb:subItem:add']">
        新增 ({{allSubItemList.length}}/5）</el-button>
      <el-table v-loading="txloading" :data="allSubItemList">
        <el-table-column label="题项内容" align="center" prop="content">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{scope.row.content}}</span>
            <el-input v-else v-model="scope.row.content" type="textarea" placeholder="请输入题项内容"
                      maxlength="200" show-word-limit />
          </template>
        </el-table-column>
        <el-table-column label="题项code" align="center" prop="code">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{scope.row.codeMc}}</span>
            <el-select v-else v-model="scope.row.code" placeholder="请选择题项code" style="width:100%">
              <el-option v-for="dict in codeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                         :value="dict.dictValue"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="是否正确答案" align="center" prop="correct">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{scope.row.correctMc}}</span>
            <el-select v-else v-model="scope.row.correct" placeholder="请选择是否正确答案"
                       style="width:100%">
              <el-option v-for="dict in mustOptions" :key="dict.dictValue" :label="dict.dictLabel"
                         :value="dict.dictValue"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{scope.row.remark}}</span>
            <el-input v-else v-model="scope.row.remark" type="textarea" placeholder="请输入备注"
                      maxlength="200" show-word-limit />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                         width="160">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit"
                       @click="handleUpdateTx(scope.row)" v-if='!scope.row.isEdit&&scope.row.id'
                       v-hasPermi="['qb:subItem:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-s-claim" v-if="scope.row.isEdit"
                       @click="handleSave(scope.row,scope.$index)">
              保存</el-button>
            <el-popconfirm title="确定删除吗？" @confirm='delTx(scope.row,scope.$index)'>
              <el-button size="mini" type="text" icon="el-icon-delete" slot="reference"
                         v-hasPermi="['qb:subItem:remove']">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm" :loadding='saveLoading'>确 定</el-button> -->
        <el-button @click="openTx=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubject, getSubject, delSubject,cshSubject, addSubject, updateSubject, exportSubject, updateSubItem, listSubItem, addSubItem, delSubItem } from "@/api/subject/subject";

export default {
  name: "Subject",
  components: {
  },
  data() {
    return {
      nowTmObj: {},
      // 遮罩层
      subItemList: [],
      txloading: false,
      openTx: false,
      saveLoading: false,
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      classOptions: [],
      subjectList: [],
      correctOptions: [],
      codeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 题库类型字典
      categoryOptions: [],
      txList: [],
      // 是否必练题字典
      mustOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subClass: null,
        category: null,
        queType: null,
        title: null,
        answer: null,
        score: null,
        must: null,
        status: null,
      },
      addList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subClass: [
          { required: true, message: "题库类别不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "题库类型不能为空", trigger: "blur" }
        ],
        queType: [
          { required: true, message: "题型不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "题干不能为空", trigger: "blur" }
        ],
        answer: [
          { required: true, message: "答案不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("bus_rylb").then(response => {
      this.categoryOptions = response.data;
    });
    this.getDicts("subject_class").then(response => {
      this.classOptions = response.data;
    });
    this.getDicts("subject_type").then(response => {
      this.txList = response.data;
    });
    this.getDicts("bus_sf").then(response => {
      this.mustOptions = response.data;
      this.correctOptions = response.data;
    });
    this.getDicts("bus_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("subject_code").then(response => {
      this.codeOptions = response.data;
    });
  },
  computed: {
    allSubItemList() {
      return this.subItemList.concat(this.addList)
    }
  },
  methods: {
    delTx(row, index) {
      if (row.id) {
        delSubItem(row.id).then(response => {
          this.msgSuccess("删除成功")
          this.seeTx()
        })
      } else {
        this.addList.splice(index - this.subItemList.length, 1)
      }
    },
    handleUpdateTx(row) {
      row.isEdit = true
    },
    handleSave(row, index) {
      if (row.id) {
        updateSubItem(row).then(response => {
          this.msgSuccess('编辑成功')
          this.seeTx()
        })
      } else {
        addSubItem(row).then(response => {
          this.addList.splice(index - this.subItemList.length, 1)
          this.msgSuccess('新增成功')
          this.seeTx()
        })
      }
    },
    handleAddTx() {
      this.addList.push({
        isEdit: true,
        "code": "",
        "content": "",
        "correct": "",
        "id": '',
        "remark": "",
        "searchValue": "",
        "subjectId": this.nowTmObj.id
      })
    },
    seeTx(row) {
      this.openTx = true
      this.txloading = true
      if (row) this.nowTmObj = row
      listSubItem(row ? row.id : this.nowTmObj.id).then(response => {
        this.subItemList = response.data.map(val => {
          val.isEdit = false
          val.codeMc = this.selectDictLabel(this.codeOptions, val.code)
          val.correctMc = this.selectDictLabel(this.correctOptions, val.correct)
          return val
        })
      }).finally(() => {
        this.txloading = false
      })
    },
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listSubject(this.queryParams).then(response => {
        this.subjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 题项code字典翻译
    codeFormat(row, column) {
      return this.selectDictLabel(this.codeOptions, row.code);
    },
    // 是否正确答案字典翻译
    correctFormat(row, column) {
      return this.selectDictLabel(this.correctOptions, row.correct);
    },
    // 题库类型字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    subClassFormat(row, column) {
      return this.selectDictLabel(this.classOptions, row.subClass);
    },
    queTypeFormat(row, column) {
      return this.selectDictLabel(this.txList, row.queType);
    },
    // 是否必练题字典翻译
    mustFormat(row, column) {
      return this.selectDictLabel(this.mustOptions, row.must);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        category: null,
        subClass: null,
        queType: null,
        title: null,
        answer: null,
        score: null,
        must: null,
        status: "1",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSubject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveLoading = true
          if (this.form.id != null) {
            updateSubject(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.saveLoading = false
            })
          } else {
            addSubject(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.saveLoading = false
            })
          }
        }
      });
    },
    handleCsh(row) {
      cshSubject().then(response => {
        this.msgSuccess("初始化成功");
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否删除所选数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSubject(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有题目数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportSubject(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
